<template>
    <div style="width: 100vw;height: 100vh">

        <el-container style="height: 100%;width: 100%">
            <el-aside width="250px">
                <el-card v-for="(item, index) of moduleBaseInfoList" shadow="hover" @click.native="cardClick(index)"
                         :class="['module-card', item.active ? 'card-active' : '']">
                    <div class="text item">
                        {{ item.moduleName }}
                    </div>
                    <div class="text item">
                        {{ item.moduleCode }}
                    </div>
                    <div>
                        <el-button style="float: right;margin-left: 10px; padding: 3px 0;color: red"
                                   @click.stop="moduleDel(index)" type="text">删除
                        </el-button>
                        <el-button style="float: right; padding: 3px 0" @click.stop="moduleUpdate(index)" type="text">
                            编辑
                        </el-button>
                    </div>
                </el-card>
            </el-aside>
            <el-container>
                <el-header>Header</el-header>
                <el-main>
                    <el-tabs v-model="typeActiveName" v-show="activeModule != null" type="card"
                             @tab-click="handleClick">
                        <el-tab-pane label="查询" name="query">
                            <el-tabs v-model="queryActiveName" @tab-click="handleQueryTabClick" tab-position="left" style="height: 100%;">
                                <el-tab-pane label="SQL配置" name="sqlConfig">
                                  <pre id="codeEditor" class="ace_editor" style="min-height:320px">
                                    <div class="ace_text-input" cssStyle="width:97.5%;height:320px;"/>
                                  </pre>
                                    <el-button type="primary" @click="querySqlSave">保存查询配置</el-button>
                                </el-tab-pane>
                                <el-tab-pane label="查询字段" name="queryField">
                                    <el-form :inline="true" :model="querySelectSearchForm" class="demo-form-inline">
                                        <el-form-item label="关键字搜索">
                                            <el-input v-model="querySelectSearchForm.keyword" placeholder="关键字"></el-input>
                                        </el-form-item>
                                        <el-form-item>
                                            <el-button type="primary" @click="doQuerySelectSearch">查询</el-button>
                                            <el-button type="primary" @click="clearQuerySelectSearchForm">清空</el-button>
                                            <el-button type="primary" @click="addQuerySelect">新增</el-button>
                                        </el-form-item>
                                    </el-form>
                                    <el-table :data="selectTableData" style="width: 100%" max-height="450">
                                        <el-table-column prop="fieldName" label="字段名" width="120"></el-table-column>
                                        <el-table-column prop="fieldAlias" label="字段别名"
                                                         width="150"></el-table-column>
                                        <el-table-column prop="fieldDesc" label="字段中文名"
                                                         width="120"></el-table-column>
                                        <el-table-column prop="isValid" label="是否生效" align="center" width="120">
                                            <template slot-scope="scope">
                                                <i :class="scope.row.isValid ? 'el-icon-check' : 'el-icon-close'"></i>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="fieldType" label="字段类型" width="120">
                                            <template slot-scope="scope">
                                                {{ getFieldType(scope.row.fieldType) }}
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="inputType" label="输入类型" width="120">
                                            <template slot-scope="scope">
                                                {{ getInputType(scope.row.inputType) }}
                                            </template>
                                        </el-table-column>
                                        <el-table-column fixed="right" label="操作" width="120">
                                            <template slot-scope="scope">
                                                <el-button @click.native.prevent="editQuerySelectField(scope.$index, scope.row)"
                                                           type="text" size="small">
                                                    编辑
                                                </el-button>
                                                <el-button @click.native.prevent="deleteQuerySelectField(scope.$index, scope.row)"
                                                           type="text" size="small" style="color: red">
                                                    移除
                                                </el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </el-tab-pane>
                                <el-tab-pane label="返回字段" name="returnField">
                                    <el-table :data="returnTableData" style="width: 100%" max-height="450">
                                        <el-table-column prop="fieldName" label="字段名" width="120"></el-table-column>
                                        <el-table-column prop="fieldAlias" label="字段别名"
                                                         width="150"></el-table-column>
                                        <el-table-column prop="fieldDesc" label="字段中文名"
                                                         width="120"></el-table-column>
                                        <el-table-column prop="isValid" label="是否隐藏" align="center" width="120">
                                            <template slot-scope="scope">
                                                <i :class="scope.row.isHidden ? 'el-icon-check' : 'el-icon-close'"></i>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="fieldType" label="字段类型" width="120">
                                            <template slot-scope="scope">
                                                {{ getFieldType(scope.row.fieldType) }}
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="inputType" label="输入类型" width="120">
                                            <template slot-scope="scope">
                                                {{ getInputType(scope.row.inputType) }}
                                            </template>
                                        </el-table-column>
                                        <el-table-column fixed="right" label="操作" width="120">
                                            <template slot-scope="scope">
                                                <el-button @click.native.prevent="editReturnSelectField(scope.$index, scope.row)"
                                                           type="text" size="small">
                                                    编辑
                                                </el-button>
                                                <el-button @click.native.prevent="deleteReturnSelectField(scope.$index, scope.row)"
                                                           type="text" size="small" style="color: red">
                                                    移除
                                                </el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </el-tab-pane>
                                <el-tab-pane label="版本管理" name="versionControl">
                                    <el-table
                                        :data="versionList"
                                        border
                                        v-loading="versionTableLoading"
                                        style="width: 60%">
                                        <el-table-column
                                            prop="id"
                                            label="版本号"
                                            width="180">
                                        </el-table-column>
                                        <el-table-column
                                            prop="createTime"
                                            label="提交日期"
                                            width="180">
                                        </el-table-column>
                                        <el-table-column
                                            prop="remark"
                                            label="变更备注"
                                            width="180">
                                        </el-table-column>
                                        <el-table-column
                                            prop="address"
                                            label="操作">
                                            <template slot-scope="scope">
                                                <el-button @click.native.prevent="queryRollback(scope.$index, scope.row)"
                                                           type="text" size="small">
                                                    回滚
                                                </el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <el-pagination
                                        @size-change="handleSizeChange"
                                        @current-change="handleCurrentChange"
                                        :current-page="versionPageNum"
                                        :page-sizes="[10, 20, 30, 40]"
                                        :page-size="versionPageSize"
                                        layout="total, sizes, prev, pager, next, jumper"
                                        :total="versionTotal">
                                    </el-pagination>

                                </el-tab-pane>
                            </el-tabs>
                        </el-tab-pane>
                        <el-tab-pane label="新增" name="add">新增</el-tab-pane>
                        <el-tab-pane label="修改" name="update">修改</el-tab-pane>
                        <el-tab-pane label="删除" name="delete">删除</el-tab-pane>
                    </el-tabs>
                </el-main>
            </el-container>
        </el-container>

        <el-dialog
                title="查询字段配置"
                :visible.sync="queryDialogVisible"
                width="40%"
                :close-on-click-modal="false">
            <el-form :model="querySelectForm" :rules="rules" ref="querySelectForm" label-width="120px" class="demo-ruleForm">
                <el-form-item label="id" prop="id">
                    <el-input v-model="querySelectForm.id" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="字段中文名称" prop="fieldDesc">
                    <el-input v-model="querySelectForm.fieldDesc"></el-input>
                </el-form-item>
                <el-form-item label="字段名" prop="fieldName">
                    <el-input v-model="querySelectForm.fieldName"></el-input>
                </el-form-item>
                <el-form-item label="字段别名" prop="fieldAlias">
                    <el-input v-model="querySelectForm.fieldAlias"></el-input>
                </el-form-item>
                <el-form-item label="字段类型" prop="fieldType">
                    <el-select v-model="querySelectForm.fieldType" placeholder="请选择字段类型">
                        <el-option label="数值" :value="0"></el-option>
                        <el-option label="string" :value="1"></el-option>
                        <el-option label="时间戳" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="输入类型" prop="inputType">
                    <el-select v-model="querySelectForm.inputType" placeholder="请选择输入类型">
                        <el-option label="文本框" :value="0"></el-option>
                        <el-option label="数值" :value="1"></el-option>
                        <el-option label="单选" :value="2"></el-option>
                        <el-option label="多选" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否生效" prop="isValid">
                    <el-radio-group v-model="querySelectForm.isValid">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="单选多选框数据来源" prop="selectorDataSource">
                    <el-input type="textarea" v-model="querySelectForm.selectorDataSource"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="queryDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitQuerySelectField">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog
            title="返回字段配置"
            :visible.sync="returnDialogVisible"
            width="40%"
            :close-on-click-modal="false">
            <el-form :model="returnSelectForm" :rules="returnRules" ref="returnSelectForm" label-width="120px" class="demo-ruleForm">
                <el-form-item label="id" prop="id">
                    <el-input v-model="returnSelectForm.id" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="字段中文名称" prop="fieldDesc">
                    <el-input v-model="returnSelectForm.fieldDesc"></el-input>
                </el-form-item>
                <el-form-item label="字段名" prop="fieldName">
                    <el-input v-model="returnSelectForm.fieldName"></el-input>
                </el-form-item>
                <el-form-item label="字段别名" prop="fieldAlias">
                    <el-input v-model="returnSelectForm.fieldAlias"></el-input>
                </el-form-item>
                <el-form-item label="字段类型" prop="fieldType">
                    <el-select v-model="returnSelectForm.fieldType" placeholder="请选择字段类型">
                        <el-option label="数值" :value="0"></el-option>
                        <el-option label="string" :value="1"></el-option>
                        <el-option label="时间戳" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="输入类型" prop="inputType">
                    <el-select v-model="returnSelectForm.inputType" placeholder="请选择输入类型">
                        <el-option label="文本框" :value="0"></el-option>
                        <el-option label="数值" :value="1"></el-option>
                        <el-option label="单选" :value="2"></el-option>
                        <el-option label="多选" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否隐藏" prop="isHidden">
                    <el-radio-group v-model="returnSelectForm.isHidden">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="单选多选框数据来源" prop="selectorDataSource">
                    <el-input type="textarea" v-model="returnSelectForm.selectorDataSource"></el-input>
                </el-form-item>
                <el-form-item label="字段转换处理javascript" prop="selectorDataSource">
                    <el-input type="textarea" v-model="returnSelectForm.fieldHandleScript"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="returnDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitreturnSelectField">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="'保存' + confirmType + '配置确认'" :visible.sync="confirmDialogVisible">
            <el-form :model="confirmForm">
                <el-form-item label="变更备注（必填）">
                    <el-input v-model="confirmForm.remark" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="confirmDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitConfig(confirmType)">确 定</el-button>
            </div>
        </el-dialog>



    </div>
</template>

<script>
import {moduleList, moduleQueryConfigDetail, moduleQueryConfigAdd, listVersion} from "@/api/module";
import {uuid} from "@/util/util";

export default {
    name: "SuperQueryIndex",
    data() {
        return {
            querySqlEditor: null,
            moduleBaseInfoList: [],
            queryActiveName: 'sqlConfig',
            typeActiveName: 'query',
            activeModule: null,
            selectTableData: [],
            returnTableData: [],
            queryDialogVisible: false,
            returnDialogVisible: false,
            confirmDialogVisible: false,
            returnSelectForm: {},
            querySelectForm: {},
            querySelectSearchForm: {},
            confirmForm: {},
            confirmType: '',
            versionList: [],
            versionPageNum: 1,
            versionPageSize: 10,
            versionTotal: 0,
            versionTableLoading: false,
            rules: {
                fieldDesc: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur' }
                ],
                fieldName: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur' }
                ],
                fieldAlias: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur' }
                ],
                fieldType: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                inputType: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                isValid: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                selectorDataSource: [
                    { required: false }
                ]
            },
            returnRules: {
                fieldDesc: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur' }
                ],
                fieldName: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur' }
                ],
                fieldAlias: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur' }
                ],
                fieldType: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                inputType: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                isHidden: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                selectorDataSource: [
                    { required: false }
                ]
            }
        }
    },
    methods: {
        //初始化代码编辑器
        initQueryEditor() {
            //获取控件   id ：codeEditor
            this.querySqlEditor = ace.edit("codeEditor");
            //设置风格和语言（更多风格和语言，请到github上相应目录查看）
            // theme = "monokai";
            //theme = "terminal";
            //语言
            // language = "sql";
            this.querySqlEditor.setTheme("ace/theme/monokai");
            this.querySqlEditor.session.setMode("ace/mode/sql");
            //字体大小
            this.querySqlEditor.setFontSize(15);
            //设置只读（true时只读，用于展示代码）
            this.querySqlEditor.setReadOnly(false);
            //自动换行,设置为off关闭
            this.querySqlEditor.setOption("wrap", "free");
            this.querySqlEditor.setOption("selectionStyle", "text");
            //启用提示菜单
            ace.require("ace/ext/language_tools");
            this.querySqlEditor.setOptions({
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true
            });
        },
        handleClick(val) {
            console.log(val)
        },
        querySqlSave() {
            this.confirmType = 'query'
            this.confirmDialogVisible = true;
        },
        cardClick(index) {
            let id = this.moduleBaseInfoList[index].id;
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            moduleQueryConfigDetail({id: id}).then(res => {
                this.activeModule = res
                this.moduleBaseInfoList.forEach(x => {
                    x.active = false
                })
                this.moduleBaseInfoList[index].active = true;
                this.queryActiveName = 'sqlConfig'
                if (this.activeModule && this.activeModule.moduleQueryVo && this.activeModule.moduleQueryVo.sqlText) {
                    this.querySqlEditor.setValue(this.activeModule.moduleQueryVo.sqlText)
                } else {
                    this.querySqlEditor.setValue('')
                }
                this.selectTableData = res.selectFieldVoList || []
                this.returnTableData = res.returnFieldVoList || []
            }).finally(() => {
                loading.close()
            })

        },
        moduleUpdate(index) {
            console.log(index)
        },
        moduleDel(index) {
            console.log(index)
        },
        getFieldType(fieldType) {
            switch (fieldType) {
                case 0:
                    return 'number'
                case 1:
                    return 'string'
                case 2:
                    return '时间戳'
                default:
                    return '未知'
            }
        },
        getInputType(inputType) {
            switch (inputType) {
                case 0:
                    return '文本框'
                case 1:
                    return '数值'
                case 2:
                    return '单选'
                case 3:
                    return '多选'
                default:
                    return '未知'
            }
        },
        editQuerySelectField(index, row) {
            this.querySelectForm = JSON.parse(JSON.stringify(row));
            this.queryDialogVisible = true;
        },
        submitQuerySelectField() {
            this.$refs['querySelectForm'].validate((valid) => {
                if (valid) {
                    if (this.querySelectForm.id) {
                        for (let i = 0; i < this.selectTableData.length; i++) {
                            if (this.selectTableData[i].id === this.querySelectForm.id) {
                                this.$set(this.selectTableData, i, this.querySelectForm)
                            }
                        }
                    } else {
                        this.querySelectForm.id = uuid()
                        this.selectTableData.unshift(this.querySelectForm)
                    }
                    this.queryDialogVisible = false;
                    this.querySelectForm = {};
                } else {
                    return false;
                }
            })
        },
        deleteQuerySelectField(index, row) {
            this.$confirm('确认移除？')
                .then(_ => {
                    this.selectTableData.splice(index, 1)
                })
                .catch(_ => {});
        },
        editReturnSelectField(index, row) {
            this.returnSelectForm = JSON.parse(JSON.stringify(row));
            this.returnDialogVisible = true;
        },
        deleteReturnSelectField(index, row) {
            this.$confirm('确认移除？')
                .then(_ => {
                    this.returnTableData.splice(index, 1)
                })
                .catch(_ => {});
        },
        submitreturnSelectField() {
            this.$refs['returnSelectForm'].validate((valid) => {
                if (valid) {
                    if (this.returnSelectForm.id) {
                        for (let i = 0; i < this.returnTableData.length; i++) {
                            if (this.returnTableData[i].id === this.returnSelectForm.id) {
                                this.$set(this.returnTableData, i, this.returnSelectForm)
                            }
                        }
                    } else {
                        this.returnSelectForm.id = uuid()
                        this.returnTableData.unshift(this.returnSelectForm)
                    }
                    this.returnDialogVisible = false;
                    this.returnSelectForm = {};
                } else {
                    return false;
                }
            })
        },
        doQuerySelectSearch() {

        },
        addQuerySelect() {
            this.querySelectForm = {}
            this.queryDialogVisible = true
        },
        clearQuerySelectSearchForm() {

        },
        submitConfig(type) {
            if (!this.confirmForm.remark) {
                return
            }
            switch (type) {
                case 'query':
                    this.saveQueryConfig();
                    break;
                default:
                    return;
            }

        },
        saveQueryConfig() {
            let activeModule = this.activeModule;
            let params = {...activeModule};
            let sqlText = this.querySqlEditor.getValue();
            let remark = this.confirmForm.remark
            if (!sqlText) {
                alert("sql未填写")
            }
            params.moduleQueryVo = {
                moduleCode: activeModule.moduleCode,
                sqlText: sqlText,
                remark: remark
            }
            params.selectFieldVoList = this.selectTableData
            params.returnFieldVoList = this.returnTableData
            moduleQueryConfigAdd(params).then(res => {
                this.confirmDialogVisible = false;
                this.confirmForm.remark = ''
                alert('保存成功')
                window.location.reload()
            })
        },
        handleQueryTabClick() {
            this.versionTableLoading = true
            let _this = this;
            let params = {
                id: _this.activeModule.id,
                pageNum: 1,
                pageSize: 10
            }
            listVersion(params).then(res => {
                _this.versionList = res.records
                _this.versionTotal = res.total
            }).finally(() => {
                this.versionTableLoading = false
            })
        },

        handleCurrentChange(val) {
            this.getVersions()
        },
        handleSizeChange(val) {
            this.getVersions()
        },
        getVersions() {
            this.versionTableLoading = true
            let _this = this;
            let params = {
                id: _this.activeModule.id,
                pageNum: _this.versionPageNum,
                pageSize: _this.versionPageSize
            }
            listVersion(params).then(res => {
                _this.versionList = res.records
                _this.versionTotal = res.total
            }).finally(() => {
                this.versionTableLoading = false
            })
        },
        queryRollback(index, row) {
            this.$confirm('确认回滚？回滚后点击保存才生效')
                .then(_ => {
                    this.reloadConfig(this.activeModule.id, row.id)
                })
                .catch(_ => {});
        },
        reloadConfig(configId, queryId) {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            moduleQueryConfigDetail({id: configId, versionId: queryId}).then(res => {
                this.activeModule = res
                this.queryActiveName = 'sqlConfig'
                if (this.activeModule && this.activeModule.moduleQueryVo && this.activeModule.moduleQueryVo.sqlText) {
                    this.querySqlEditor.setValue(this.activeModule.moduleQueryVo.sqlText)
                } else {
                    this.querySqlEditor.setValue('')
                }
                this.selectTableData = res.selectFieldVoList || []
                this.returnTableData = res.returnFieldVoList || []
            }).finally(() => {
                loading.close()
            })
        }


    }
    ,
    mounted() {
        this.initQueryEditor();
        moduleList().then(res => {
            res.forEach(x => {
                x.active = false
            })
            this.moduleBaseInfoList = res;
        })


    }
}
</script>

<style scoped>
.el-header, .el-footer {
    background-color: #B3C0D1;
    color: #333;

}

.el-aside {
    background-color: #D3DCE6;
    color: #333;

}

.el-main {


}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 5px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

.box-card {
    /*width: 480px;*/
}

.module-card {
    margin-bottom: 3px;
    margin-top: 3px;
    cursor: pointer;
}

.card-active {
    background-color: #42b983;
}

.el-icon-check {
    color: green;
    font-size: large;
}

.el-icon-close {
    color: red;
    font-size: large;
}

/*body > .el-container {*/
/*    margin-bottom: 40px;*/
/*}*/


</style>